/**
 * 
 */
package org.corpus.english.controller;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import org.corpus.english.model.Word;
import org.corpus.english.model.WordCategoryData;
import org.corpus.english.model.WordCategoryDataHome;
import org.corpus.english.model.WordHome;
import org.corpus.english.model.WordResultConfig;
import org.zkoss.zk.ui.Component;
import org.zkoss.zk.ui.Executions;
import org.zkoss.zk.ui.util.GenericForwardComposer;
import org.zkoss.zkplus.databind.AnnotateDataBinder;
import org.zkoss.zul.Div;


/**
 * @author robbiecheng
 *
 */
public class WordSearchController_ extends GenericForwardComposer{
	private WordHome wordDao = new WordHome();
	private WordCategoryDataHome wordCateDao = new WordCategoryDataHome();
	private Word current = new Word();
	private WordResultConfig config = new WordResultConfig(true, true, true);
	private List searchResults;
	

	public void doBeforeComposeChildren(Component comp){
		if (Executions.getCurrent().getParameter("id") != null){
			String wordId = Executions.getCurrent().getParameter("id");
			current = wordDao.findById(Integer.parseInt(wordId));
		} else if (Executions.getCurrent().getParameter("word") != null && Executions.getCurrent().getParameter("sent") != null){
			current.setWord(Executions.getCurrent().getParameter("word"));
			current.setSentences(Executions.getCurrent().getParameter("sent"));
		}
	}
	
	public List getAllWordCategorys(){
		return wordCateDao.findByExample(new WordCategoryData());
	}
	
	public Word getCurrent() {
		return current;
	}
	
	public WordResultConfig getConfig(){
		return config;
	}
	public int getWordCount(){
		return wordDao.findByExample(new Word()).size();
	}
	//search
	private Div searchResult;
	public void onClick$searchBtn(){
		if (session.getAttribute("querys") == null)
			UpdateManager.updateSearchResult(searchResult, UpdateManager.WORD_SEARCH_RESULT, wordDao.findByQuery(current), config);
		else{
			List querys = (List) session.getAttribute("querys");
			List results = new ArrayList();
			for (Iterator iterator = querys.iterator(); iterator.hasNext();) {
				Word query = (Word) iterator.next();
				results.addAll(wordDao.findByQuery(query));
			}
			UpdateManager.updateSearchResult(searchResult, UpdateManager.WORD_SEARCH_RESULT, results, config);
			session.setAttribute("querys", null);
		}
	}
	
	//continue to search
	AnnotateDataBinder binder;
	public void onClick$continueToSearch(){
		if (session.getAttribute("querys") == null)
			session.setAttribute("querys", new ArrayList());
		else{
			List querys = (List) session.getAttribute("querys");
			querys.add(current); 
			current = new Word();
			binder.loadAll();
		}
	}
}
